<?php
/**
 * Akimimi Front
 * CategorySearchView
 * by xiaoyuemian
 */

require_once '../app/views/BaseView.php';

class CategorySearchViewL2V3 extends BaseView {

    public $searchKey = null;
    public $metadatas;
    public $products;
    public $pager;
    public $sort;
    public $filter;
    public $category_id;
    public $navigation;
    public $categoryChildren;
//    public $categorySiblings;

    public function getPage() {
        $arr_navsetting = array();
        $arr_categoryies = $this->navigation;
        while($arr_category=array_pop($arr_categoryies)){
            if(!empty($arr_categoryies)){
                if(empty($arr_category['parent_id']))
                    $arr_navsetting[] = array('url'=>'/c/index/'.$arr_category['url_title'], 'text'=>$arr_category['short_name']);
                else
                    $arr_navsetting[] = array('url'=>'/c/search/'.$arr_category['id'], 'text'=>$arr_category['short_name']);
            }else{
            	$arr_lastCategory = $arr_category;
                $arr_navsetting[] = array('text'=>$arr_category['short_name']);
            }
        }
        $this->setPageTitle($arr_lastCategory['short_name']);
        $this->addCSS('category_search_test.css');
        $this->addCSS('myaccountleftnav.css');
        $this->addJS('category_search_test.js');
        require_once '../app/views/MyAccoutLeftNavView.php';
        $myAccountLeftNavView = new MyAccountLeftNav();
        $header = '';
        $str_result = $header
                    . "<div>"
                    . $this->getNavigation($arr_navsetting)
                    . "<div class='p2_main'>"
                    . $this->getFilterBlock()
                    . $this->getSearchResultBlock()
                    . '</div></div>';
        return $this->getHtmlPage($str_result);
    }

    /**
     * 过滤器部分
     *
     * @return string
     */
    public function getFilterBlock() {
        return "<div class='p2_sort'>"
               . "<div class='p2_sorttop'>&nbsp;</div>"
               . "<div class='p2_sorttilte'><img src='" . ConfigConstants::getTImagePath() . "/p2_sorttitleimg.gif' /></div>"
               . "<div class='p2_sortul'>"
               . "<form id='sortForm' style='margin:0px;'>"
               . "<input type='hidden' id='categoryid' value='{$this->category_id}' />"
               . "<table cellpadding='0' cellspacing='0' border='0' style='width:98%;margin:auto;'>"
               . $this->getCategoryList()
               . $this->getSortList() 
               . '</table></form>'
               . '</div>'
               . "</div>";
    }

    protected function getCategoryList(){
    	$str_result = '';
    	/*if(empty($this->categoryChildren))		//最后一级category，显示其sibling category
    	{
    		if(!empty($this->categorySiblings))
    		{
    		    $str_result.= '<tr>';
				$str_result.= "<th style='width:70px;'>{$this->navigation[1]['short_name']}</th>";
				$str_result.= '<td>' . $this->getCategoriesInList($this->categorySiblings, $this->category_id, $this->navigation[0]['parent_id']) . '</td>';
				$str_result.= "</tr>";
    		}
    		else
    		    HttpUtil::renderError();
    	}
    	else*/									//第二级category，显示其所有child category
    	if(!empty($this->categoryChildren))
    	{
    		    $str_result.= '<tr>';
    		    //<input id='parent_category_{$this->navigation[0]['id']}' type='hidden' name='category[{$this->navigation[0]['id']}]' />
    		    $str_result.= "<th style='width:100px;'>{$this->navigation[0]['short_name']}</th>";
				$str_result.= '<td>' . $this->getCategoriesInList($this->categoryChildren, $this->category_id, $this->navigation[0]['id']) . '</td>';
				$str_result.= "</tr>";
    	}
    	
    	return $str_result;
    }
    
    protected function getCategoriesInList($categories, $selectedCid, $parentCid) {
        if(empty($categories))
            return '';
        $str_result = "<ul><li class='p2_sortli0" . (($selectedCid != $parentCid) ? '1' : '2' ) . "' cid='{$parentCid}'>" . SEARCHALLOPTIONSTXT . '</li>';
        if (!empty($categories)) {
            $int_number = 0;
            foreach ($categories as $ctgr) {
                $int_number++;
                if($int_number > 20)
                    break;
                if ($selectedCid == $ctgr['id'])
            	   $str_result.= "<li class='p2_sortli02' cid='{$ctgr['id']}'>{$ctgr['short_name']}</li>";
                else
            	   $str_result.= "<li class='p2_sortli01' cid='{$ctgr['id']}'>{$ctgr['short_name']}</li>";
            }
        }
        $str_result.= '</ul>';
        
        return $str_result;
    }
    
    /**
     * 获得筛选条件清单
     *
     * @return string
     */
    protected function getSortList(){
        $arr_metadatas = $this->metadatas;
        if (empty($arr_metadatas))
            return '';
        $str_result = "";
//        $str_result.= "<input type='hidden' id='sortby_price' name='sortby_price' />";
//        $str_result.= "<input type='hidden' id='sortby_created' name='sortby_created' />";
//        $str_result.= "<input type='hidden' id='pageNumber' name='page' />";
        $bool_firstRows = !empty($this->categoryChildren);
		if(!empty($arr_metadatas)){
			foreach ($arr_metadatas as $int_index => $arr_metadata) {
				//print_r($arr_metadata);exit;
				/**
				 * @desc 生成一行
				 */
				$str_result.= '<tr>';
				$str_result.= "<th style='width:100px;" . ($bool_firstRows? "border-top:1px dashed #dedede;'" : '') . "'>{$arr_metadata['metadata_title']}<input id='metadata_{$arr_metadata['metadata_id']}' type='hidden' name='metadata[{$arr_metadata['metadata_id']}]' /></th>";
				$str_result.= '<td' . ($bool_firstRows? " style='border-top:1px dashed #dedede;'" : '') . '>' . $this->getSortListOptions($arr_metadata['options'],$arr_metadata['metadata_id']) . '</td>';
				$str_result.= "</tr>";
				if (!$bool_firstRows)
				   $bool_firstRows = true;
			}
		}
        return $str_result;
    }

    /**
     * 列出一行筛选条件
     *
     * @param array $arr_options
     * @param int $int_parentid
     * @return string
     */
    protected function getSortListOptions($arr_options, $int_parentid) {
        $bool_selectOther = false;
        if (!empty($arr_options)&&!empty($this->filter)) {
            foreach ($arr_options as $arr_option) {
                if (array_key_exists('auto_metadata_'.$int_parentid,$this->filter) && in_array($arr_option['option_id'],$this->filter))
            	   $bool_selectOther = true;
            }
        }
        $str_result = "<ul><li class='p2_sortli0" . ($bool_selectOther ? '1' : '2' ) . "' parentid='{$int_parentid}' selfid='0'>" . SEARCHALLOPTIONSTXT . '</li>';
        if (!empty($arr_options)) {
            $int_number = 0;
            foreach ($arr_options as $arr_option) {
                $int_number++;
                if($int_number > 20)
                    break;
                if (!empty($this->filter) && array_key_exists('auto_metadata_'.$int_parentid,$this->filter) && in_array($arr_option['option_id'],$this->filter))
            	   $str_result.= "<li class='p2_sortli02' parentid='{$int_parentid}' selfid='{$arr_option['option_id']}'>{$arr_option['option_title']}</li>";
                else
            	   $str_result.= "<li class='p2_sortli01' parentid='{$int_parentid}' selfid='{$arr_option['option_id']}'>{$arr_option['option_title']}</li>";
            }
        }
        $str_result.= '</ul>';
        return $str_result;
    }

    /**
     * 显示搜索结果。在使用Ajax方法显示搜索结果时也调用该方法。
     *
     * @param array $arr_products
     * @param array $arr_sort
     * @param int $int_countrows
     * @return string
     */
    public function getSearchResultBlock($arr_products=null, $arr_sort=null, $arr_pager=null) {
        if(is_null($arr_products))
            $arr_products = $this->products;
        if(is_null($arr_sort))
            $arr_sort = $this->sort;
        if(is_null($arr_pager))
            $arr_pager = $this->pager;
        
        //搜索结果，$arr_pager['countrows']为结果数
        $str_result = "<div id='searchResultBlock' class='p2_search'>"
               . "<div class='p2_title'><a name='searchresultplace'><img src='" . ConfigConstants::getTImagePath() . "/p2_searchbg.gif' /></a><p>" . sprintf(SEARCHRESULTNUMBERROWSTXT, "<span>{$arr_pager['countrows']}</span>") . '</p></div>';
        if(!empty($arr_products)){
            $str_result.= "<div class='p2_searchtop'></div>"
                        . $this->getSearchResultTitle($arr_sort, $arr_pager)
                        . $this->getSearchResultContent($arr_products)
                        . $this->getSearchResultFooter($arr_pager);
        }
        $str_result.= '</div>';
        return $str_result;
    }

    /**
     * 结果集的排序选择部分
     *
     * @param array $arr_sort
     * @return string
     */
    protected function getSearchResultTitle($arr_sort, $arr_pager){
        $str_result = "<div class='p2_searchtilte'><div class='p2_searchtitle_div'>";
        if(is_null($this->searchKey)){
        	//xiaoyuemian:默认排序没有链接？
             $str_result.=
                   "<div class='p1'>" . SEARCHSORTBYTXT . '</div>'
                   . "<div class='p2'><img src='" . ConfigConstants::getTImagePath() . "/p2_searchdiv1.gif' onclick=\"if(event){\$('#sortby_price_select').val(0); \$('#sortby_created_select').val(0); formatFormData(0);}\" /></div>"
                   . "<div class='p33'>"
                   . "<select onchange=\"if(event){\$('#sortby_created_select').val(0); formatFormData(0);}\" id='sortby_price_select' style='margin-top:5px;*margin-top:0px;'>
                    <option value='0' " . (empty($arr_sort['price'])?"selected='selected'":'') . '>' . SEARCHSORTBYPRICEOPT . "</option>
                    <option value='1' " . ($arr_sort['price']>0?"selected='selected'":'') . '>' . SEARCHSORTBYPRICEOPT.SEARCHORDERASCOPT . "</option>
                    <option value='-1' " . ($arr_sort['price']<0?"selected='selected'":'') . '>' . SEARCHSORTBYPRICEOPT.SEARCHORDERDESCOPT . "</option>
                  </select>"
               . "<select onchange=\"if(event){\$('#sortby_price_select').val(0); formatFormData(0);}\" id='sortby_created_select' style='margin-top:5px;*margin-top:0px;'>
                    <option value='0' " . (empty($arr_sort['created'])?"selected='selected'":'') . '>' . SEARCHSORTBYCREATEDOPT . "</option>
                    <option value='1' " . ($arr_sort['created']>0?"selected='selected'":'') . '>' . SEARCHSORTBYCREATEDOPT.SEARCHORDERASCOPT . "</option>
                    <option value='-1' " . ($arr_sort['created']<0?"selected='selected'":'') . '>' . SEARCHSORTBYCREATEDOPT.SEARCHORDERDESCOPT . "</option>
                  </select>"
               . '</div>';
        }
        $str_result .= "</div><div class=\"p2_searchtilte_page\">";
    	$totalPage = Pager::GetCountPage($arr_pager['countrows'], $arr_pager['pagesize']);
        if($arr_pager['nowpage'] < $totalPage)
            $str_result .= "<p class='s_1'><a href='javascript:void(0);' style='margin-left:5px;' onclick=\"formatFormData("
                    . ($arr_pager['nowpage'] + 1)
                    .")\" >" . "下一页" . "</a></p>";
        $str_result .= "<p class='s_2'>".$this->getPager($arr_pager)."</p>";
        
        if($arr_pager['nowpage'] > 1)
        	$str_result .= "<p class='s_1'><a href='javascript:void(0);' onclick=\"formatFormData("
                    . ($arr_pager['nowpage'] - 1)
                    .")\" >" . "上一页" . "</a></p>";
        $str_result .= '</div></div>';
        
        /*$str_result .= '</div><div class="p2_searchtilte_page">';
        if($arr_pager['nowpage'] > 1)
            $str_result .= '<p class="s_1"><a href="javascript:void(0);" '
                    . ' onclick="formatFormData('
                    . ($arr_pager['nowpage'] - 1)
                    .')" >上一页</a></p>';
        $str_result .= '<p class="s_2">'
                    . $this->getPager($arr_pager)
                	.'</p>';
        if($arr_pager['nowpage'] < Pager::GetCountPage($arr_pager['countrows'], $arr_pager['pagesize']))
            $str_result .= '<p class="s_1"><a href="javascript:void(0);" '
                    . ' onclick="formatFormData('
                    . ($arr_pager['nowpage'] + 1)
                    .')" >下一页</a></p>';
        $str_result .= "</div></div>";*/
        
        return $str_result;
    }

    /**
     * 结果集的商品内容显示部分
     *
     * @param array $arr_products
     * @return string
     */
    protected function getSearchResultContent($arr_products){
        $str_result = "<div class='tab_box'><div class='p2_search01'>";
        if (!empty($arr_products)) {
            foreach ($arr_products as $arr_product){
                $str_result.= $this->getSearchResultProduct($arr_product);
            }
        }
        $str_result.= '</div></div>';
        return $str_result;
    }

    /**
     * 显示一个商品
     *
     * @param array $arr_product
     * @return string
     */
    protected function getSearchResultProduct($arr_product){
        return "<div class='p2_search02_l2v2'>"
               . "<img style='cursor:pointer;' "
                   . "onclick=\"window.open('/p/" . urlencode($arr_product['url_title']) . "'); \""
                   . "src='" . (empty($arr_product['image_name']) ? ConfigConstants::getDefaultProductImagePath('200'):ConfigConstants::getProductImagePath($arr_product['image_folder'],$arr_product['image_name'],'200')) 
                   . "' />"
               . "<p class=\"title_1\">" . SEARCHLISTPRICETXT . "<span>￥</span><b>{$arr_product['list_price']}</b></p>"
               . "<p class=\"title_2\" style='cursor:pointer;' onclick=\"window.open('/p/" . urlencode($arr_product['url_title']) . "');\">{$arr_product['title']}</p>"
               . '</div>';
    }

    /**
     * 结果集的分页条
     *
     * @param array $arr_pager
     * @return string
     */
    protected function getSearchResultFooter($arr_pager){
        require_once '../app/util/Pager.php';
        $htmlurl='<center><script type="text/javascript"><!--
				google_ad_client = "pub-1231013902088237";
				/* 728x90, 创建于 09-11-9 */
				google_ad_slot = "7118374628";
				google_ad_width = 728;
				google_ad_height = 90;
				//-->
				</script>
				<script type="text/javascript" src=" http://pagead2.googlesyndication.com/pagead/show_ads.js"></script></center>';
        $str_result = "<div class=\"bottom_page\">";
//    	$str_result = '';
    	if($arr_pager['nowpage'] > 1)
        	$str_result .= "<p class='s_1'><a href='javascript:void(0);' onclick=\"formatFormData("
                    . ($arr_pager['nowpage'] - 1)
                    .")\" >" . "上一页" . "</a></p>";
        $str_result .= "<p class='s_2'>".$this->getPager($arr_pager)."</p>";
        $totalPage = Pager::GetCountPage($arr_pager['countrows'], $arr_pager['pagesize']);
        if($arr_pager['nowpage'] < $totalPage)
            $str_result .= "<p class='s_1'><a href='javascript:void(0);' style='margin-left:5px;' onclick=\"formatFormData("
                    . ($arr_pager['nowpage'] + 1)
                    .")\" >" . "下一页" . "</a></p>";
        $str_result .= "<p class='s_3'>共{$totalPage}页，当前第{$arr_pager['nowpage']}页</p>";
        if($totalPage > 1)
            $str_result .= '<p class="s_4"><input type="text" id="pageNumberToJump" class="input_text"></p>'
                        . '<input type="hidden" id="totalPage" value="'. $totalPage .'">'
                        . "<p class='s_5'><a href='javascript:void(0);' onclick=\"jampToCertanPage()\""
                        ." >" . "跳转" . "</a></p>";
        $str_result .= '</div>';
        
        return $str_result;
    }
    
/**
     * 结果集的分页条
     *
     * @param array $arr_pager
     * @return string
     */
    protected function getPager($arr_pager){
        require_once '../app/util/PagerNew.php';
        $pager = new PagerNew(null, 'pageNumber');
        $pager->curNumStyle = '';
        $pager->numLinkStyle = '';
        $pager->spaceElement = "<a class='p_dd'>...</a>";
        $pager->pagerCssFront = '';
        $pager->pagerCssBack = '';
        $pager->setJavascriptFunction('formatFormData');
        return $pager->paginate($arr_pager['nowpage'],$arr_pager['countrows'],'/a/categorysearch/page/', $arr_pager['pagesize']);
    }

    /**
     * 结果集的分页条[用于/s]
     *
     * @param array $arr_pager
     * @return string
     */
    /*protected function getSearchFooter($arr_pager){
        require_once '../app/util/Pager.php';
        $pager = new Pager();
        return "<div class='p2_page'>" . $pager->paginate($arr_pager['nowpage'],$arr_pager['countrows'],"/s/{$this->searchKey}/") . '</div>';
    }*/

    /**
     * 商品的属性显示
     *
     * @param array $arr_product
     * @return string
     */
    /*protected function productAttribute($arr_product){
        $str_result = '<p>';
        $str_result.= SEARCHMARKETINGPRICETXT . "<span class='p2_money'>" . $arr_product['marketing_price'] . '</span><br />';
        if( $arr_product['sale_price'] != $arr_product['list_price'] ){
            $str_result.= SEARCHLISTPRICETXT . "<span class='p2_money'>" . $arr_product['list_price'] . '</span><br />';
            $str_result.= SEARCHSALEPRICETXT . "<span class='p2_money01'>" . $arr_product['sale_price'] . '</span>';
        }else{
            $str_result.= SEARCHLISTPRICETXT . "<span class='p2_money01'>" . $arr_product['sale_price'] . '</span>';
        }
        $str_result.= '</p>';
        return $str_result;
    }*/

}